# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.

import typing as t

from flask_sqlalchemy.pagination import QueryPagination

from ksai.serializer import JsonSerializable


class Query(JsonSerializable):
    page: int = 1
    offset: int = 15
    total: int = 0
    total_page: int = 0,
    keyword: t.Optional[str] = None
    items: t.Optional[t.Any] = None

    def __init__(self):
        pass

    def init(self, params: t.Dict[str, t.Any], offset: t.Optional[int] = 16) -> 'Query':
        if params:
            self.page = int(params.get('page', 1) or 1)
            self.offset = int(params.get('offset', offset) or offset)
            self.total = 0
            self.total_page = 0
            self.keyword = params.get('keyword', '').strip()
        return self

    def pagination(self, pagination: t.Optional[QueryPagination]) -> 'Query':
        if pagination is not None:
            self.total = pagination.total
            self.items = pagination.items
            self.total_page = pagination.pages
        return self

    def serialize(self) -> t.Optional[dict]:
        return {
            "total": self.total,
            "total_page": self.total_page,
            "offset": self.offset,
            "items": self.items,
        }
